<template>
	<view class="content">
		<view :style='{"width":"100%","padding":"0 0 40rpx 0","background":"#F3F3F3","flexDirection":"column","display":"flex","height":"auto"}'>
			<view class="list-swiper-4" :style='{"width":"100%","position":"relative","height":"360rpx"}' @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
				<view :style='{"width":"100%","position":"absolute","top":"0%","left":"0%","background":"#fff","height":"360rpx"}' class="item animate__animated" :class="prevNumList4 == index  ? 'animate__backOutRight' : (numList4 == index  ? 'animate__backInLeft' : '')" v-for="(swiper,index) in swiperList" :key="index" v-if="numList4 == index || prevNumList4 == index">
					<image :style='{"width":"100%","objectFit":"cover","display":"block","height":"360rpx"}' mode="aspectFill" :src="baseUrl+swiper.img" @tap="onSwiperTap(swiper)"></image>
					<view :style='{"padding":"8rpx 20rpx","margin":"-20rpx 0 0 0","transform":"translate3d(-50%, -50%, 0)","top":"50%","color":"#000","left":"50%","background":"rgba(255, 255, 255, 0.3)","display":"none","lineHeight":"1.5","fontSize":"40rpx","position":"absolute"}'>{{ swiper.title }}</view>
				</view>
				<view class="animate__navigation" :style='{"alignItems":"center","left":"0%","bottom":"0%","background":"rgba(0,0,0,.3)","display":"flex","width":"100%","position":"absolute","justifyContent":"center","height":"40rpx"}'>
					<block v-for="(swiper,index) in swiperList" :key="index">
						<text class="navigation-item" v-if="numList4 == index" :style='{"width":"16rpx","margin":"0 4rpx","borderRadius":"100%","background":"#F7EFDB","height":"16rpx"}'></text>
						<text class="navigation-item" v-if="numList4 != index" :style='{"width":"16rpx","margin":"0 4rpx","borderRadius":"100%","background":"#fff","height":"16rpx"}'></text>
					</block>
				</view>
			</view>
			<!-- menu -->
			<view v-if="true" class="menu_view" :style="{'padding': '30rpx', 'margin': '30rpx 0', 'background': '#fff', 'display': 'flex', 'width': '100%', 'justify-content': 'space-between', 'flex-wrap': 'wrap', 'height': 'auto', 'box-sizing': 'border-box', 'box-shadow': '0 4rpx 12rpx rgba(0,0,0,0.1)', 'border-radius': '16rpx'}">
				<!-- 使用固定菜单项渲染 -->
				<view class="menu-item" v-for="(item, index) in fixedMenuItems" :key="index" @tap="onMenuItemTap(item.path)" :style="{'padding': '40rpx 0', 'margin': '0 0 40rpx 0', 'width': '100%', 'height': 'auto', 'display': 'flex', 'flex-direction': 'row', 'align-items': 'center', 'justify-content': 'center', 'border': '2rpx solid #e0e0e0', 'border-radius': '16rpx', 'box-shadow': '0 2rpx 8rpx rgba(0,0,0,0.05)', 'transition': 'all 0.3s'}">
					<view class="iconarr" :class="item.icon" :style="{'border-radius': '100%', 'padding': '0', 'margin': '0 30rpx 0 0', 'color': '#9EEEEB', 'background': 'none', 'display': 'block', 'width': '100rpx', 'font-size': '100rpx', 'line-height': '100rpx', 'height': '100rpx'}"></view>
					<view class="text" :style="{'padding': '0', 'margin': '0', 'color': '#333', 'width': 'auto', 'font-size': '40rpx', 'line-height': '50rpx', 'text-align': 'left', 'font-weight': '500'}">{{item.title}}</view>
				</view>
			</view>
		</view>

		<customTabbar :pagePath="'../../pages/index/index'" :userRole="userRole"></customTabbar>
	</view>
</template>

<script>
	import customTabbar from '@/components/customtabbar/index.vue'
    import menu from '@/utils/menu'
	import '@/assets/css/global-restaurant.css'
	import uniIcons from "@/components/uni-ui/lib/uni-icons/uni-icons.vue"
	export default {
		components: {
			uniIcons,
			customTabbar
		},
		data() {
			return {
				startX: 0, 
				prevNumList4: '',
				numList4: 0,
				timerList4: null,
				flagList4: false,
				navigationActive: {"width":"16rpx","margin":"0 4rpx","borderRadius":"100%","background":"#F7EFDB","height":"16rpx"},
				navigationDefault: {"width":"16rpx","margin":"0 4rpx","borderRadius":"100%","background":"#fff","height":"16rpx"},
				options2: {
					effect: 'flip',
					loop : true
				},
				options3: {
					effect: 'cube',
					loop : true,
					cubeEffect: {
						shadow: true,
						slideShadows: true,
						shadowOffset: 20,
						shadowScale: 0.94,
					}
				},
				rows: 2,
				column: 4,
				iconArr: [
					'cuIcon-same',
					'cuIcon-deliver',
					'cuIcon-evaluate',
					'cuIcon-shop',
					'cuIcon-ticket',
					'cuIcon-cascades',
					'cuIcon-discover',
					'cuIcon-question',
					'cuIcon-pic',
					'cuIcon-filter',
					'cuIcon-footprint',
					'cuIcon-pulldown',
					'cuIcon-pullup',
					'cuIcon-moreandroid',
					'cuIcon-refund',
					'cuIcon-qrcode',
					'cuIcon-remind',
					'cuIcon-profile',
					'cuIcon-home',
					'cuIcon-message',
					'cuIcon-link',
					'cuIcon-lock',
					'cuIcon-unlock',
					'cuIcon-vip',
					'cuIcon-weibo',
					'cuIcon-activity',
					'cuIcon-friendadd',
					'cuIcon-friendfamous',
					'cuIcon-friend',
					'cuIcon-goods',
					'cuIcon-selection'
				],
				role : '',
				menuList: [],
				swiperMenuList:[],
				user: {},
				tableName:'',

				//轮播
				swiperList: [],
				fuwuxiangmulist: [],
				news: [],
				scrollTop: 0,
                menuList:[],
				userRole: 'default', // 默认用户角色
				
				// 定义固定的菜单项，根据图片中的菜单
				fixedMenuItems: [
					{
						title: "公告咨询",
						icon: "cuIcon-news",
						path: "pages/announcement/list"
					},
					{
						title: "留言互动",
						icon: "cuIcon-message",
						path: "pages/forum-index/forum-index"
					},
					{
						title: "我的发帖",
						icon: "cuIcon-profile",
						path: "pages/forum-my/forum-my"
					},
					{
						title: "排行榜",
						icon: "cuIcon-taxi",
						path: "pages/paihangbang/list"
					}
				]
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		},
		watch: {
		},
		mounted() {
			console.log(this.menuList);
			
		},
		computed: {
			baseUrl() {
				return this.$base.url;
			},
		},
		async onLoad(){
			let appToken = localStorage.getItem("appToken")
			if(appToken == null){
				   uni.reLaunch({
				      url: '/pages/login/login',
				      success: () => {
				        console.log('强制跳转到登录页');
				      }
				    });
			}
			
			this.menuColor = this.menuColor.sort(()=> {
				return (0.5-Math.random());
			});
		},
		async onShow() {
			if (this.timerList4&&this.timerList4!=null) clearInterval(this.timerList4)
			this.swiperMenuList = []
			this.role = uni.getStorageSync("appRole");
			// 根据角色设置userRole
			if (this.role === 'admin' || this.role === 'yuangong') {
				this.userRole = 'admin';
			} else {
				this.userRole = 'default';
			}
			let table = uni.getStorageSync("nowTable");
			let res = await this.$api.session(table);
			this.user = res.data;
			this.tableName = table;
			let menus = menu.list();
			this.menuList = menus;
			
			// 处理菜单数据，获取前端菜单
			this.processMenuItems();
			
			this.menuList.forEach((item,key) => {
				if(key==0) {
					item.frontMenu.forEach((item2,key2) => {
						if(item2.child[0].buttons.indexOf("查看")>-1) {
							this.swiperMenuList.push(item2);
						}
					})
				}
			})
			// let res;
			// 轮播图
			let swiperList = []
			res = await this.$api.list('config', {
				page: 1,
				limit: 5
			});
			for (let item of res.data.list) {
				if (item.name.indexOf('轮播图') >= 0 && item.value && item.value!="" && item.value!=null ) {
					swiperList.push({
						img: item.value,
						title: item.name,
						url: item.url
					});
				}
			}
			if (swiperList) {
				this.swiperList = swiperList;
			}
			
			this.prevNumList4 = this.swiperList.length - 1
			this.timerList4 = setInterval(this.autoPlayList4, 3000)

			// 推荐信息
			this.getRecommendList()
			this.getHomeList()
			this.getNewsList()
		},
		methods: {
			// 处理菜单数据，从menu.json提取所需菜单项
			processMenuItems() {
				
				// 使用固定的菜单项
				// 可以根据用户角色从menuList中提取额外的菜单项
				// this.fixedMenuItems已包含图片中显示的4个菜单项
			},
			scrollTopClick(){
				uni.pageScrollTo({
					scrollTop: 0
				})
			},
			uGetRect(selector, all) {
				return new Promise(resolve => {
					uni.createSelectorQuery()
					.in(this)
					[all ? 'selectAll' : 'select'](selector)
					.boundingClientRect(rect => {
						if (all && Array.isArray(rect) && rect.length) {
							resolve(rect);
						}
						if (!all && rect) {
							resolve(rect);
						}
					})
					.exec();
				});
			},
			cloneData(data) {
				return JSON.parse(JSON.stringify(data));
			},
			newsTabClick2(index){
				this.newsIndex2 = index
				this.getNewsList()
			},
			async getNewsList(){
				let res;
				let params = {
					page: 1,
					limit: 4,
					sort: 'id',
					order: 'desc',
				}
				// 公告资讯
				res = await this.$api.list('news', params)
				this.news = res.data.list
			},
			homeTabClick2(index,name){
				this['home' + name + 'Index2'] = index
				this.getHomeList()
			},
			async getHomeList(){
				let res;
				let params;
			},
			recommendTabClick2(index,name){
				this[name + 'Index2'] = index
				this.getRecommendList()
			},
			async getRecommendList(){
				let res;
				let params;
				// 推荐信息
				params = {
					page: 1,
					limit: 4,
				}
				if(uni.getStorageSync("appUserid")) {
					res = await this.$api.recommend2('fuwuxiangmu', params);
				} else {
					res = await this.$api.recommend('fuwuxiangmu', params);
				}
				this.fuwuxiangmulist = res.data.list
				

			},
			autoPlayList4() {
				this.prevNumList4 = this.numList4
			
				this.numList4++
				if (this.numList4 == this.swiperList.length) this.numList4 = 0
			},
			touchStart(event) {
				this.startX = event.touches[0].clientX
				
				clearInterval(this.timerList4)
				this.flagList4 = true
			},
			touchMove(event) {
				const currentX = event.touches[0].clientX;
				const deltaX = currentX - this.startX;
				
				if (deltaX > 50) {
					// 向右滑动逻辑
					if (this.flagList4) {
						this.flagList4 = false
						
						this.prevNumList4 = this.numList4
						this.numList4++
						if (this.numList4 == this.swiperList.length) this.numList4 = 0
					}
					
				} else if (deltaX < -50) {
					// 向左滑动逻辑
					if (this.flagList4) {
						this.flagList4 = false
						
						this.prevNumList4 = this.numList4
						this.numList4--
						if (this.numList4 < 0) this.numList4 = this.swiperList.length - 1
					}
				}
			},
			touchEnd() {
				this.startX = 0
				this.timerList4 = setInterval(this.autoPlayList4, 3000)
				this.flagList4 = false
			},
			//轮播图跳转
			onSwiperTap(e) {
				if(e.url) {
					if (e.url.indexOf('https') != -1) {
						// #ifdef MP-WEIXIN
						uni.navigateTo({
						    url: '../../common/linkOthers/linkOthers?url=' + encodeURIComponent(e.url),
						});
						return false
						// #endif
						window.open(e.url)
					} else {
						this.$utils.jump(e.url)
					}
				}
			},
			// 新闻详情
			onNewsDetailTap(id) {
				this.$utils.jump(`../news-detail/news-detail?id=${id}`)
			},
			// 推荐列表点击详情
			onDetailTap(tableName, id) {
				this.$utils.jump(`../${tableName}/detail?id=${id}`)
			},
			onPageTap(tableName){
				uni.navigateTo({
					url: `../${tableName}/index`,
					fail: function(){
						uni.switchTab({
							url: `../${tableName}/list`
						});
					}
				});
				// this.$utils.jump(`../${tableName}/list`)
			},
			onPageTap2(index) {
				let url = '../' + index + '/list'
				if(index=='forum'){
					url = '../forum-index/forum-index'
				}
				uni.setStorageSync("useridTag",0);
				uni.navigateTo({
					url: url,
					fail: function() {
						uni.switchTab({
							url: url
						});
					}
				});
			},
			onMenuItemTap(path) {
				// 处理完整路径
				console.log('导航到: ', path);
				if (path.startsWith('pages/')) {
					// 去掉开头的pages/，统一格式为 ../xxx/yyy
					const pathSegments = path.split('/');
					if (pathSegments.length >= 3) {
						const pagePath = '../' + pathSegments[1] + '/' + pathSegments[2];
						console.log('处理后路径: ', pagePath);
						uni.navigateTo({
							url: pagePath,
							fail: (err) => {
								console.error('导航失败: ', err);
								// 尝试使用switchTab
								uni.switchTab({
									url: pagePath,
									fail: (switchErr) => {
										console.error('switchTab也失败: ', switchErr);
										// 如果是特殊页面，使用自定义处理
										if (path.includes('forum-my')) {
											this.$utils.jump('../forum-my/list');
										}
									}
								});
							}
						});
					}
				} else {
					// 保留原来的逻辑作为后备
					this.onPageTap2(path.split('/').pop());
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		min-height: calc(100vh - 44px);
		box-sizing: border-box;
	}
	.list-swiper-4 .animate__animated {
		--animate-delay: 300ms;
	}

	.menu_view {
		padding: 30rpx;
		margin: 30rpx 0;
		background: #fff;
		display: flex;
		width: 100%;
		justify-content: space-between;
		flex-wrap: wrap;
		height: auto;
		box-sizing: border-box;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
		border-radius: 16rpx;
	}
	.menu_view .menu-item {
		padding: 40rpx 0;
		margin: 0 0 40rpx 0;
		width: 100%;
		height: auto;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		border: 2rpx solid #e0e0e0;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
		transition: all 0.3s;
	}
	.menu_view .menu-item:active {
		transform: scale(0.95);
	}
	.menu_view .menu-item .iconarr {
		border-radius: 100%;
		padding: 0;
		margin: 0 30rpx 0 0;
		color: #9EEEEB;
		background: none;
		display: block;
		width: 100rpx;
		font-size: 100rpx;
		line-height: 100rpx;
		height: 100rpx;
	}
	.menu_view .menu-item .text {
		padding: 0;
		margin: 0;
		color: #333;
		width: auto;
		font-size: 40rpx;
		line-height: 50rpx;
		text-align: left;
		font-weight: 500;
	}
</style>

